<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
import resize from './mixins/resize'

export default {
  name:'RevenueTrends',
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '280px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    },
    setOptions(data) {
      const xAxisData = data.map(item => { return item.mon })
      const amountData = data.map(item => { return item.amount })
      var option = {
        title: {
          text: '营收趋势',
          textStyle:{
            color:'#6e6868'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            let result = params[0].name + '<br/>';
            result += params[0].seriesName + ': ' + params[0].value + ' 元' + '<br/>';
            return result;
          },
        },
        legend: {
          data: ['金额']
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisLabel:{
            color:'#6e6868'
          }
        },
        yAxis: {
          type: 'value',
          axisLabel:{
            color:'#6e6868',
            formatter: '{value} 元',
          },
          splitLine: {
            lineStyle:{
              type: 'dashed',
            }
          },
        },
        series: [
          {
            name: '金额',
            type: 'bar',
            data: amountData,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#50FFE5FF' },   // 渐变的起始颜色
                { offset: 1, color: '#87cefa' },   // 渐变的结束颜色
              ]),  // 设置柱状图的颜色
              opacity: 0.8,
              barBorderRadius: 5,
            }
          }
        ]
      };
      this.chart.setOption(option)
    }
  }
}
</script>
